package com.lanyou.cook.web;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.DataDictionaryValue;
import com.lanyou.cook.repository.DataDictionaryValueRepository;

/**
 * 数据字典相关业务控制层
 * @author 仇伟业
 *
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/dataDictionaryValues")
public class DataDictionaryValueController {

	@Autowired
	private DataDictionaryValueRepository dataDictionaryValueRepository;
	@Autowired
	private EntityManager entityManager;
	/**
	 * 获取数据字典值的集合
	 * @param typeCode	类型:String 数据字典类型
	 * @return 类型:List<DataDictionaryValue> 数据字典值集合
	 */
	@RequestMapping("/search/findByTypeCode")
	public List<DataDictionaryValue> findByTypeCode(String typeCode){
		return dataDictionaryValueRepository.findById_TypeCode(typeCode);
	}
	
	@RequestMapping("/search/findByTypeCo")
	public String findByTypeCodes(String typeCode){
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Tuple> cq = cb.createTupleQuery();

		// 构建FROM
		Root<DataDictionaryValue> root = cq.from(DataDictionaryValue.class);

		// 构建WHERE部分
		List<Predicate> predicatesList = new ArrayList<>();
		if (StringUtils.isNotBlank(typeCode)) {
			predicatesList.add(cb.equal(root.get("id").get("typeCode"), typeCode));
		}
		cq.where(predicatesList.toArray(new Predicate[predicatesList.size()]));

		// 构建GROUP BY部分
		cq.groupBy(root.get("valueName"));

		// 构建SELECT部分
		cq.multiselect(root.get("id").get("typeCode").alias("typeCode"),root.get("id").get("valueCode").alias("valueCode"),root.get("valueName").alias("valueName"));
		// 执行查询
		TypedQuery<Tuple> q = entityManager.createQuery(cq);
		List<Tuple> queryResult = q.getResultList();
		
		JsonArray jsonDatas = new JsonArray();
		for (Tuple tuple : queryResult) {
			String  Code = tuple.get("typeCode", String.class);
			String  valueCode = tuple.get("valueCode", String.class);
			String  valueName = tuple.get("valueName", String.class);
			
			JsonObject jo = new JsonObject();
			jo.addProperty("valueName", valueName);
			jo.addProperty("valueCode", valueCode);
			jo.addProperty("typeCode", Code);
			jsonDatas.add(jo);
		}
		return jsonDatas.toString();	
	}
}
